<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>ajax文件上传</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <style type="text/css">
      .fileBtn {
        width: 80px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background-color: dodgerblue;
        color: #fff;
        cursor: pointer;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <div id="fileBtn" class="fileBtn">选择文件</div>
    <img id="img0" width="300px"/>
    <div id="submit" class="fileBtn">上传</div>
    <br/>
    <a href="/index2" target="_blank">方式二</a>
  </body>
  <script type="text/javascript">
    
    var fileBtn;
    $("#fileBtn").click(function () {
      //使用$()返回一个文件域
      fileBtn = $("<input type='file' />");
      fileBtn.click();
      fileBtn.change(function () {
        var objUrl = getObjectURL(this.files[0]); //获取文件信息  
        var file = fileBtn.get(0).files[0];
        console.log("objUrl = " + objUrl);
        if (objUrl) {
          $("#img0").attr("src", objUrl);
        }
        
      });
    });
    
    $("#submit").click(function () {
      var formData = new FormData();
      var file = fileBtn.get(0).files[0];
      formData.append("image", file);
      console.log(formData);
      $.ajax({
        url: "/upload",
        data: formData,
        type: "post",
        dataType: "text",
        processData: false,
        contentType: false,
        success: function (data) {
          alert(data)
        },
        error: function (data) {
          console.log(data)
        }
      });
    });
    
    
    function getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) { // mozilla(firefox)  
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) { // webkit or chrome  
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    }
  </script>
</html>
